package com.qf.base.controller;

import com.qf.base.util.JwtUtil;
import com.qf.base.vo.UserVO;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.base.controller
 * @Description: controller的标准定义, 集成各种公共方法
 * @Date 2022/7/30 17:37
 */
public class BaseController {
    /**
     * 获取当前线程绑定的request的方法
     */
    public HttpServletRequest request(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    /**
     * 获取当前线程绑定的response方法
     */
    public HttpServletResponse response(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

    /**
     * 获取当前登录的用户实体
     */
    public UserVO user(){
        String token = request().getHeader("token");
        UserVO userVO = JwtUtil.checkToken(token);
        return userVO;
    }

    /**
     * 获取当前登录用户的id
     */
    public Long userId(){
        UserVO user = user();
        return user == null ? null : user.getId();
    }
}
